<%@ page import="java.sql.*, java.util.*, javax.servlet.http.Cookie" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 检查登录
    Cookie[] cookies = request.getCookies();
    String logonusername = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("logonusername".equals(cookie.getName())) {
                logonusername = cookie.getValue(); // 获取Cookie的值
                break;
            }
        }
    }

    if (logonusername == null) {
        out.println("<script>alert('删除留言请先登录！');window.location.href='../logon.jsp';</script>");
        return; 
    }

    // 获取请求参数
    String mid = request.getParameter("mid");
    if (mid == null || mid.isEmpty()) {
        out.println("<script>alert('删除失败！缺少参数。');window.location.href='../index.jsp';</script>");
        return; 
    }

    // 初始化
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/message", "message", "message");

        // 删除
        String sql = "DELETE FROM mess WHERE id = ? AND name = ?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, mid);
        pstmt.setString(2, logonusername);

        int rows = pstmt.executeUpdate();

        if (rows > 0) {
            out.println("<script>window.location.href='../index.jsp';</script>");
        } else {
            out.println("<script>alert('删除留言失败，请确保您有权限删除该留言。');window.location.href='../index.jsp';</script>");
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        out.println("<script>alert('数据库加载失败！');window.location.href='../index.jsp';</script>");
    } catch (SQLException e) {
        e.printStackTrace();
        out.println("<script>alert('数据库操作失败！请重试或联系管理员。');window.location.href='../index.jsp';</script>");
    } finally {
        try {
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
%>